/*
 * @Author: szx
 * @Date: 2022-03-08 15:25:23
 * @LastEditTime: 2022-03-08 15:40:56
 * @Description:
 * @FilePath: \leetcode\400-499\450\450_2.js
 */
/**
 * @param {TreeNode} root
 * @param {number} key
 * @return {TreeNode}
 */
var deleteNode = function (root, key) {
    // 空节点，直接返回
    if (!root) return null;
    if (root.val == key) {
        if (!root.left && !root.right) return null;
        if (!root.left) return root.right;
        else if (!root.right) return root.left;
        else {
            let right = root.right;
            while (right.left) right = right.left;
            right.left = root.left;
            root = root.right;
            return root;
        }
    } else if (key < root.val) root.left = deleteNode(root.left, key);
    else root.right = deleteNode(root.right, key);
    return root;
};
